﻿using System;
using System.Collections.Generic;

using System.Text;

using System.Data;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Configuration;
using System.Threading;
using System.Windows.Forms;
using RegexJson.Common;
using System.Text.RegularExpressions;
namespace RegexJson
{
    public class KeyWordSearch
    {
       
        int rcvNum = 30;
        string rcvPath = "";
      
        bool isStart = false;
        List<KeyWordInfo> qpList = new List<KeyWordInfo>();
        public delegate void KeyWordSearchEventHandle(object sender, KeyWordSearchArgs msg);
        public event KeyWordSearchEventHandle KeyWordSearchHandle;
        Thread threadReceive=null;
        KeyWordSearchArgs upArgs = null;
        private KeyWordSearch() { }
        public KeyWordSearch(List<KeyWordInfo> _qpList)
        {
            try
            {
                qpList = _qpList;
               
                
            }
            catch (Exception ex)
            {
                AppLog.Write(ex.Message, AppLog.LogMessageType.Fatal);
                throw new Exception("KeyWordSearch配置出错！！");
            }

        }

      
        /// <summary>
        /// 上传
        /// </summary>
        public void Update()
        {
            try
            {
               
                string strBaidu="http://www.baidu.com/s?wd={0}";
                string strGoogle = "http://www.google.com.hk/search?q={0}";
                string strContent = "";
                Regex reg = null;
                string strTemp = "";
                upArgs = new KeyWordSearchArgs();
                upArgs.CountNum = qpList.Count;
                updateMessage(upArgs);
                int intIndex = 0;
                foreach (KeyWordInfo qp in qpList)
                {
                   
                    if (isStart)
                    {
                        intIndex++;
                        try
                        {
                            strContent = Utils.GetRequestString(string.Format(strBaidu, Utils.UrlDecode(qp.KeyWord)), 16000, 0, Encoding.GetEncoding("utf-8"), "");

                        }
                        catch (Exception ex)
                        {
                            AppLog.Write(ex.Message, AppLog.LogMessageType.Error, ex);
                        }

                        if (strContent.Length > 200)
                        {


                            upArgs = new KeyWordSearchArgs();
                            upArgs.IsEnd = false;
                            reg = new Regex("EC_mr15", RegexOptions.IgnoreCase);
                            upArgs.JingJiaNum = (reg.Matches(strContent).Count - 1) / 2;
                            upArgs.KeyWord = qp.KeyWord;
                            strTemp = GetCutString(strContent, "<span class=\"nums\" style=\"margin-left:120px\">百度为您找到相关结果约", "个</span>").Trim();
                            strTemp = strTemp.Replace(",", "");
                            upArgs.BaiduIndexNum = Utils.StringToInt(strTemp, 0);
                            upArgs.IndexNum = intIndex;
                        }
                        string tm = Utils.RndNum(4);
                        string strcookie= string.Concat("PREF=ID=ebee2a2469eeec36:U=aaba75410adf7253:FF=2:LD=zh-CN:NW=1:TM=138268",tm,":LM=138268",tm,":S=mF8_FnKfRF-XfUwa;  path=/; domain=.google.com.hk");
                        try
                        {
                            strContent = Utils.GetRequestString(string.Format(strGoogle, Utils.UrlDecode(qp.KeyWord)), 16000, 0, Encoding.GetEncoding("gb2312"),strcookie );
                        }
                        catch (Exception ex)
                        {
                            AppLog.Write(ex.Message, AppLog.LogMessageType.Error, ex);
                        }
                        strTemp = GetCutString(strContent, "<div id=\"resultStats\">找到约", "条结果</div>").Trim();
                        strTemp = strTemp.Replace(",", "");
                        upArgs.GoogleIndexNum = Utils.StringToInt(strTemp, 0);
                        if (KeyWordSearchHandle != null)
                        {
                            updateMessage(upArgs);
                        }
                        else
                        {
                            throw new Exception("KeyWordSearch初始化错误");
                           
                        }
                       
                    }
                }
                upArgs = new KeyWordSearchArgs();
                upArgs.IsEnd = true;
                if (KeyWordSearchHandle != null)
                {
                    updateMessage(upArgs);
                }
                isStart = false;
               
            }
            catch (Exception ex)
            {
                AppLog.Write(ex.Message, AppLog.LogMessageType.Error);
            }
        }

        protected string GetCutString(string inputstring, string leftTag, string rightTag)
        {
            Regex reg = new Regex(leftTag + @"[\s|\S]*?" + rightTag, RegexOptions.IgnoreCase);
            string str = reg.Match(inputstring).Value;

            str = str.Replace(leftTag, "").Replace(rightTag, "");

            return str;

        }


        private void updateMessage(KeyWordSearchArgs upArgs)
        {
            if (KeyWordSearchHandle != null)
            {
                KeyWordSearchHandle(this, upArgs);
            }

        }
        public void Dispose()
        {
            isStart = false;
            if (threadReceive != null)
            {
                threadReceive.Abort();
            }
        }
        public void Start()
        {
            if (!isStart)
            {
                isStart = true;
                if (threadReceive == null)
                {
                    threadReceive = new Thread(Update);
                    threadReceive.Start();
                }
                else
                {
                    threadReceive = new Thread(Update);
                    threadReceive.Start();
                }
            }
            else
            {
                MessageBox.Show("已经开始上传!");
            }
        }
        public void Stop()
        {
            isStart = false;
            if (threadReceive != null)
            {
                threadReceive.Abort();
            }

        }
       
    }

    public class KeyWordSearchArgs : EventArgs
    {
        private string keyWord = "";
        private int jingJiaNum = 0;
        private Int32 baiduIndexNum = 0;
        private Int32 googleIndexNum = 0;
        private Int32 indexNum = 0;
        private Int32 countNum = 0;
        public bool IsEnd { get; set; }

        public Int32 IndexNum
        {
            get { return indexNum; }
            set { indexNum = value; }
        }
        public Int32 CountNum
        {
            get
            {
                return countNum;
            }
            set { countNum = value; }
        }
        public string KeyWord
        {
            get { return keyWord; }
            set { keyWord = value; }
        }

        public int JingJiaNum
        {
            get { return jingJiaNum; }
            set { jingJiaNum = value; }
        }

        public Int32 BaiduIndexNum
        {
            get { return baiduIndexNum; }
            set { baiduIndexNum = value; }
        }

        public Int32 GoogleIndexNum
        {
            get { return googleIndexNum; }
            set { googleIndexNum = value; }
        }
    }
}
